package com.ruoyi.merchant.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.merchant.domain.Merchant;
import com.ruoyi.merchant.service.IMerchantService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 商家信息管理Controller
 * 
 * @author ruoyi
 * @date 2025-07-28
 */
@RestController
@RequestMapping("/ruoyi/merchant")
public class MerchantController extends BaseController
{
    @Autowired
    private IMerchantService merchantService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询商家信息管理列表
     */
    // @PreAuthorize("@ss.hasPermi('ruoyi:merchant:list')")
    @GetMapping("/list")
    public TableDataInfo list(Merchant merchant)
    {
        startPage();
        List<Merchant> list = merchantService.selectMerchantList(merchant);
        return getDataTable(list);
    }

    /**
     * 导出商家信息管理列表
     */
    // @PreAuthorize("@ss.hasPermi('ruoyi:merchant:export')")
    @Log(title = "商家信息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Merchant merchant)
    {
        List<Merchant> list = merchantService.selectMerchantList(merchant);
        ExcelUtil<Merchant> util = new ExcelUtil<Merchant>(Merchant.class);
        util.exportExcel(response, list, "商家信息管理数据");
    }

    /**
     * 获取商家信息管理详细信息
     */
    // @PreAuthorize("@ss.hasPermi('ruoyi:merchant:query')")
    @GetMapping(value = "/{merchantId}")
    public AjaxResult getInfo(@PathVariable("merchantId") Long merchantId)
    {
        return success(merchantService.selectMerchantByMerchantId(merchantId));
    }

    /**
     * 新增商家信息管理
     */
    // @PreAuthorize("@ss.hasPermi('ruoyi:merchant:add')")
    @Log(title = "商家信息管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Merchant merchant)
    {
        return toAjax(merchantService.insertMerchant(merchant));
    }

    /**
     * 修改商家信息管理
     */
    // @PreAuthorize("@ss.hasPermi('ruoyi:merchant:edit')")
    @Log(title = "商家信息管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Merchant merchant)
    {
        // 获取原始商家信息
        Merchant original = merchantService.selectMerchantByMerchantId(merchant.getMerchantId());
        if (original == null) {
            return AjaxResult.error("找不到对应的商家信息");
        }

        // 获取商家用户绑定的用户ID信息
        Long merchantUserId = original.getUserId();
        if (merchantUserId == null) {
            return AjaxResult.error("商家未绑定用户");
        }

        // 获取旧的认证状态
        String oldStatus = original.getCertificationStatus();
        // 获取新的认证状态
        String newStatus = merchant.getCertificationStatus();

        // 执行商家信息更新
        int result = merchantService.updateMerchant(merchant);

        SysUser merchantUser = new SysUser();

        // 检查认证状态变化并更新角色 '认证状态：0=待审核 1=已通过 2=已拒绝'
        if ("1".equals(oldStatus) && !"1".equals(newStatus)) {

            // 从已认证变为非认证状态，角色恢复为104
            merchantUser.setUserId(merchantUserId);
            Long[] roleIds = {104L};
            merchantUser.setRoleIds(roleIds);

            userService.updateUser(merchantUser);
//            SysUser user = new SysUser();
//            user.setUserId(original.getUserId());
//            user.setRoleIds(new Long[]{104L});
//            userService.updateUser(user);
        } else if (!"1".equals(oldStatus) && "1".equals(newStatus)) {
            // 从非认证变为已认证状态，角色设置为101
            merchantUser.setUserId(merchantUserId);
            Long[] roleIds = {101L};
            merchantUser.setRoleIds(roleIds);

            userService.updateUser(merchantUser);
//            SysUser user = new SysUser();
//            user.setUserId(original.getUserId());
//            user.setRoleIds(new Long[]{101L});
//            userService.updateUser(user);
        }

        return toAjax(result);
        // return toAjax(merchantService.updateMerchant(merchant));
    }

    /**
     * 删除商家信息管理
     */
    // @PreAuthorize("@ss.hasPermi('ruoyi:merchant:remove')")
    @Log(title = "商家信息管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{merchantIds}")
    public AjaxResult remove(@PathVariable Long[] merchantIds)
    {
        return toAjax(merchantService.deleteMerchantByMerchantIds(merchantIds));
    }

    /**
     * 查询商家表中是否存在某个 userId
     */
    @GetMapping("/selectMerchantWhereUserId")
    public AjaxResult selectMerchantWhereUserId()
    {
        // 获取当前用户ID
        Long userId = getUserId();
        Long selectMerchantWhereUserId = merchantService.selectMerchantWhereUserId(userId);
        if (selectMerchantWhereUserId == 0) {
            return success(false);
        } else {
            return success(true);
        }
    }

    /**
     * 根据userId查询商家信息
     */
    @GetMapping("/selectMerchantByUserId")
    public AjaxResult selectMerchantByUserId()
    {
        // 获取当前用户ID
        Long userId = getUserId();
        Merchant merchant = merchantService.selectMerchantByUserId(userId);
        return success(merchant);
    }

    /**
     * 审核商家认证状态
     *
     * @param merchantId 商家唯一标识ID
     * @return AjaxResult 返回操作结果，包含成功/失败状态及提示信息
     *                    成功时返回1，失败时返回错误信息
     */
    // @PreAuthorize("@ss.hasPermi('ruoyi:merchant:edit')")
    @Log(title = "审核认证状态", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/{merchantId}")
    public AjaxResult approved(@PathVariable Long merchantId)
    {
        // 获取商家信息
        Merchant merchantInfo = merchantService.selectMerchantByMerchantId(merchantId);
        if (merchantInfo == null) {
            return AjaxResult.error("找不到对应的商家信息");
        }
        // 获取商家用户绑定的用户ID信息
        Long merchantUserId = merchantInfo.getUserId();
        if (merchantUserId == null) {
            return AjaxResult.error("商家未绑定用户");
        }
        // 更新商家角色
        SysUser merchantUser = new SysUser();
        merchantUser.setUserId(merchantUserId);

        Long[] roleIds = {101L};
        merchantUser.setRoleIds(roleIds);

        userService.updateUser(merchantUser);

        // 获取商家id后修改商家认证状态
        Merchant merchant = new Merchant();
        merchant.setMerchantId(merchantId);
        merchant.setCertificationStatus("1"); // 认证成功
        merchant.setUpdateTime(DateUtils.getNowDate());
        merchant.setUpdateBy(getUsername());

        return toAjax(merchantService.updateMerchant(merchant));
    }
}
